import { useState } from "react";
import { observer } from "Mobx-react";
import { Radio, Checkbox, Select, Rate, Input, Button, Modal, Tooltip, Form, message } from "antd";
import type { CheckboxChangeEvent } from "antd/es/checkbox";
import { EyeOutlined, EyeInvisibleOutlined } from "@ant-design/icons";
import TextArea from "antd/es/input/TextArea";
import { questionnaire } from "@/stores/questionnaire";
import { modalState } from "@/stores/modalState";
import type { questionType, controlLogicType } from "@/types/index";
import { typeEnum, validateOption, typeSelect, matrixSelect, columnSelect, columnFillSelect } from "@/assets/common/enums";
import { scoreOptionInit } from "@/utils/index";
import { isBasicsOption, isMatrixOption, generateColumn, chooseMinMax } from "@/utils/calculation";
import SliderItem from "@/components/SliderItem/SliderItem";
import RichTinymce from "@/components/RichTinymce/RichTinymce";
import MatrixItem from "@/components/MatrixItem/MatrixItem";
import SurveyMenu from "./ItemSon/SurveyMenu";
import BasicsEditor from "./ItemSon/BasicsEditor";
import SliderOption from "./ItemSon/SliderOption";
import MatrixEditor from "./ItemSon/MatrixEditor";
import { SurveyItemContent } from "../stye";

interface SurveyItemType {
  question: questionType;
  index: number;
  serialNum: number;
  insertNum: number;
  showConcern: string;
  optionLogic: controlLogicType[];
}

const { RADIO, CHECKBOX, DROP, SCORE, FILL, PAGING, PARAGRAPH, SLIDER, MATRIX_SLIDER, MATRIX_RADIO, MATRIX_CHECKBOX } = typeEnum;

const serialRemoveType = [PARAGRAPH, PAGING];
const noConcernItem = [FILL, SLIDER, MATRIX_RADIO, MATRIX_CHECKBOX, MATRIX_SLIDER];
function SurveyItem({ question, index = 0, serialNum = 0, insertNum = 0, showConcern = "", optionLogic = [] }: SurveyItemType) {
  const scoreOption = question.option.length;
  const matrixOptionShow = isMatrixOption(question.type);
  const [formState, setState] = useState<any>(matrixOptionShow ? {} : "");

  const insertClick = () => {
    let insert = index;
    if (insert === insertNum) insert = -2;
    questionnaire.insert(insert);
  };
  //点击编辑
  const editClick = () => {
    questionnaire.editCount(question.id);
  };
  //点击必答
  const checkboxChange = (e: CheckboxChangeEvent) => {
    questionnaire.mustSelect(index, e.target.checked ? 1 : 0);
  };
  //切换类型
  const typeChange = (value: typeEnum) => {
    const text = value !== MATRIX_SLIDER && question.type !== MATRIX_SLIDER ? `是否将${question.type}题改为${value}题？` : `将${question.type}题改为${value}题选项会发生改变，是否修改？`;
    Modal.confirm({
      title: "提示",
      content: text,
      okText: "确认",
      cancelText: "取消",
      onOk() {
        if (value === FILL) {
          const id = question.id;
          const controlLogic = questionnaire.controlLogic.filter(item => item.childId === id || item.questionIds.includes(String(id)));
          const controlOption = questionnaire.controlOption.filter(item => item.childId === id || item.questionIds.includes(String(id)));
          //判断是否有逻辑关联
          if (controlLogic.length || controlOption.length) {
            Modal.confirm({
              title: "提示",
              content: `题目有关联控制逻辑，修改题目类型，和题目相关的逻辑控制会删除，是否继续？`,
              okText: "确认",
              cancelText: "取消",
              onOk() {
                questionnaire.typeModify(index, value, id);
              }
            });
          } else {
            questionnaire.typeModify(index, value);
          }
        } else {
          questionnaire.typeModify(index, value);
        }
      }
    });
  };
  //选项个数
  const scoreOptionChange = (num: number) => {
    questionnaire.scoreOptionModify(index, num);
  };
  //选项逻辑控制
  const optionLogicText = (id: number, control: controlLogicType[]) => {
    for (const item of control) {
      if (id === item.optionId) {
        return `（${questionnaire.logicText(item)}）`;
      }
    }
    return "";
  };
  // 复制
  const copyClick = () => {
    const copy = { ...question };
    questionnaire.copy(copy, index);
  };
  //删除
  const erasureClick = () => {
    Modal.confirm({
      title: "提示",
      content: `确认删除？`,
      okText: "确认",
      cancelText: "取消",
      onOk() {
        const id = question.id;
        const controlLogic = questionnaire.controlLogic.filter(item => item.childId === id || item.questionIds.includes(String(id)));
        const controlOption = questionnaire.controlOption.filter(item => item.childId === id || item.questionIds.includes(String(id)));
        //判断是否有逻辑关联
        if (controlLogic.length || controlOption.length) {
          Modal.confirm({
            title: "提示",
            content: `题目有关联控制逻辑，删除题目，和题目相关的逻辑控制会删除，是否继续？`,
            okText: "确认",
            cancelText: "取消",
            onOk() {
              questionnaire.erasure(id, index);
            }
          });
        } else {
          questionnaire.erasure(id, index);
        }
      }
    });
  };
  //选项添加
  const optionAddClick = (optionIndex: number) => {
    if (optionIndex === -2) {
      const text = question.option.map(item => item.content).join("\n");
      modalState.getBatchAdd(text, index);
    } else {
      questionnaire.optionAdd(index, optionIndex);
    }
  };
  const optionRemoveClick = (optionIndex: number, optionId: number) => {
    if (question.option.length > 1) {
      const id = question.id;
      let bool = false;
      // 判断是否存在逻辑
      for (const item of questionnaire.controlLogic) {
        const questionIdsArray = item.questionIds.split(",");
        const idIndex = questionIdsArray.indexOf(String(id));
        if (idIndex !== -1) {
          bool = item.parentAnswer.split("|")[idIndex].split(",").includes(String(optionId));
          if (bool) break;
        }
      }
      // 判断是存在选项关联逻辑
      if (!bool) {
        for (const item of questionnaire.controlOption) {
          if (item.childId === id && item.optionId === optionId) {
            bool = true;
            break;
          }
          const questionIdsArray = item.questionIds.split(",");
          const idIndex = questionIdsArray.indexOf(String(id));
          if (idIndex !== -1) {
            bool = item.parentAnswer.split("|")[idIndex].split(",").includes(String(optionId));
            if (bool) break;
          }
        }
      }
      //判断是否有逻辑关联
      if (bool) {
        Modal.confirm({
          title: "提示",
          content: `题目选项有关联控制逻辑，删除选项，和题目相关的逻辑控制会删除，是否继续？`,
          okText: "确认",
          cancelText: "取消",
          onOk() {
            questionnaire.optionRemove(index, optionIndex, optionId);
          }
        });
      } else {
        questionnaire.optionRemove(index, optionIndex);
      }
    } else {
      const text = question.children && question.children.length === 0 ? "不能删除所有选项" : "不能删除所有列";
      message.warning(text);
    }
  };
  //选项移动
  const optionMoveClick = (optionIndex: number, action: string) => {
    if (optionIndex == 0 && action == "上") return;
    questionnaire.optionMove(index, optionIndex, action);
  };
  //移动
  const moveClick = (action: string) => {
    questionnaire.move(index, action);
  };
  //题目关联
  const concernClick = (state: number) => {
    console.log("state", state);
    const id = question.id;
    const title = question.type !== PARAGRAPH ? question.title : PARAGRAPH;
    const controlLogic = questionnaire.controlLogic.find(item => item.childId === id);
    const questionList: questionType[] = questionnaire.question;
    switch (state) {
      case 1: {
        const data = questionList
          .slice(0, index)
          .filter(item => !serialRemoveType.includes(item.type))
          .map((item, index) => ({ ...item, title: index + 1 + "." + item.title }))
          .filter(item => !noConcernItem.includes(item.type));
        if (data.length === 0) return message.info("此题前面没有选项题，无法设置关联逻辑！");
        modalState.frontOpen(data, id, title, controlLogic);
        return;
      }
      case 2: {
        if (!controlLogic) return message.info("此题没有关联逻辑，无法复制！");
        const data2 = questionList.slice(index + 1).filter(item => item.type !== typeEnum.PAGING);
        modalState.copyOpen(data2, id, title, controlLogic);
        return;
      }
      case 3: {
        const data3 = questionList
          .slice(0, index)
          .filter(item => !serialRemoveType.includes(item.type))
          .map((item, index) => ({ ...item, title: index + 1 + "." + item.title }))
          .filter(item => !noConcernItem.includes(item.type));
        const controlOption = questionnaire.controlOption?.filter(item => item.childId === id);
        modalState.optionOpen(data3, title, questionList[index].option, id, controlOption);
        return;
      }
    }
  };
  return (
    <SurveyItemContent className={question.isHide === 1 ? "hide" : ""}>
      {question.type === PARAGRAPH ? (
        <div dangerouslySetInnerHTML={{ __html: question.title }}></div>
      ) : question.type === PAGING ? (
        <div className="survey-paging">{`第${question.currentPage}页（共${questionnaire.totalPage}页）`}</div>
      ) : (
        <div className={`survey-title${question.must && " required"}`}>
          {serialNum}.{question.title}
        </div>
      )}
      <div className="survey-option">
        {question.type === RADIO ? (
          <Radio.Group className="grid" style={generateColumn(question.column)}>
            {question.option.map(subItem => (
              <Radio className="flex item-option" key={subItem.id} value={subItem.id}>
                {subItem.content}
                {optionLogic.length > 0 && <span className="item-logic">{optionLogicText(subItem.id, optionLogic)}</span>}
              </Radio>
            ))}
          </Radio.Group>
        ) : question.type === CHECKBOX ? (
          <Checkbox.Group className="grid" style={generateColumn(question.column)}>
            {question.option.map(subItem => (
              <Checkbox className="flex item-option" key={subItem.id} value={subItem.id}>
                {subItem.content}
                {optionLogic.length > 0 && <span className="item-logic">{optionLogicText(subItem.id, optionLogic)}</span>}
              </Checkbox>
            ))}
          </Checkbox.Group>
        ) : question.type === DROP ? (
          <Select className="drop-down" placeholder="请选择下拉列表" options={question.option} fieldNames={{ label: "content", value: "id" }} />
        ) : question.type === SCORE ? (
          <Rate count={scoreOption} />
        ) : question.type === FILL ? (
          <>{question.column === 1 ? <Input /> : <TextArea rows={question.column}></TextArea>}</>
        ) : question.type === SLIDER ? (
          <SliderItem value={formState} option={question.option} onChange={(value: number) => setState(value)} />
        ) : (
          matrixOptionShow && (
            <Form layout="vertical">
              <MatrixItem question={question}></MatrixItem>
            </Form>
          )
        )}
        {showConcern && <div className="show-concern">{showConcern}</div>}

        {questionnaire.editId != question.id ? (
          <SurveyMenu
            insert={insertNum !== index}
            type={question.type}
            insertClick={insertClick}
            editClick={editClick}
            copyClick={copyClick}
            erasureClick={erasureClick}
            moveClick={moveClick}
          ></SurveyMenu>
        ) : (
          <div className="item-editor">
            {question.type !== PARAGRAPH ? (
              <>
                <div className="editor-title">
                  <div className="title flex-between">
                    <span>题目标题：</span>
                    <span className="survey-hide" onClick={() => questionnaire.whetherHide(index, question.isHide)}>
                      {question.isHide === 1 ? (
                        <Tooltip title="显示题目">
                          <EyeOutlined />
                        </Tooltip>
                      ) : (
                        <Tooltip title="隐藏题目">
                          <EyeInvisibleOutlined />
                        </Tooltip>
                      )}
                    </span>
                  </div>
                  <Input value={question.title} onChange={e => (question.title = e.target.value)}></Input>
                </div>
                <div className="editor-type flex align-items">
                  {isBasicsOption(question.type) ? (
                    <Select value={question.type} options={typeSelect} style={{ width: 90, marginRight: 10 }} onChange={typeChange} />
                  ) : (
                    matrixOptionShow && <Select value={question.type} options={matrixSelect} style={{ width: 110, marginRight: 10 }} onChange={typeChange} />
                  )}
                  <Checkbox className="editor-option" checked={question.must === 1} onChange={checkboxChange}>
                    必答
                  </Checkbox>
                  {question.type === CHECKBOX && (
                    <>
                      <Select value={question.chooseMin} options={chooseMinMax(question, false)} style={{ width: 120, marginRight: 10 }} onChange={value => (question.chooseMin = value)} />
                      <Select value={question.chooseMax} options={chooseMinMax(question, true)} style={{ width: 120, marginRight: 10 }} onChange={value => (question.chooseMax = value)} />
                    </>
                  )}
                  {question.type === FILL ? (
                    <>
                      <Select value={question.validateType} options={validateOption} style={{ width: 110, marginRight: 10 }} onChange={value => (question.validateType = value)} />
                      <Select value={question.column} options={columnFillSelect} style={{ width: 110 }} onChange={value => (question.column = value)} />
                    </>
                  ) : (
                    (question.type === RADIO || question.type === CHECKBOX) && (
                      <Select value={question.column} options={columnSelect} style={{ width: 110 }} onChange={value => (question.column = value)} />
                    )
                  )}
                </div>
              </>
            ) : (
              <RichTinymce initialValue={question.title} onEditorChange={(content: string) => (question.title = content)}></RichTinymce>
            )}
            {isBasicsOption(question.type) ? (
              <BasicsEditor option={question.option} optionAddClick={optionAddClick} optionRemoveClick={optionRemoveClick} optionMoveClick={optionMoveClick}></BasicsEditor>
            ) : question.type === SCORE ? (
              <div className="score-option">
                选项个数：<Select style={{ width: 200 }} value={scoreOption} options={scoreOptionInit(10)} fieldNames={{ label: "content", value: "id" }} onChange={scoreOptionChange}></Select>
              </div>
            ) : (
              matrixOptionShow && <MatrixEditor question={question} index={index}></MatrixEditor>
            )}
            {(question.type === SLIDER || question.type === MATRIX_SLIDER) && <SliderOption option={question.option}></SliderOption>}
            <div className="logic-set flex align-items">
              <span>逻辑设置：</span>
              <a onClick={() => concernClick(1)}>题目向前关联</a>
              <a onClick={() => concernClick(2)}>复制向前关联</a>
              {(question.type === RADIO || question.type === CHECKBOX || question.type === DROP) && <a onClick={() => concernClick(3)}>选项关联</a>}
            </div>
            <Button type="primary" block size="large" onClick={() => questionnaire.resetting()}>
              完成编辑
            </Button>
          </div>
        )}
      </div>
    </SurveyItemContent>
  );
}

export default observer(SurveyItem);
